package com.example.cloud.controller.system;

import com.alibaba.fastjson.JSONArray;
import com.example.cloud.controller.common.BaseController;
import com.example.cloud.dao.mongdb.system.MongoRoleRepository;
import com.example.cloud.model.system.Menu;
import com.example.cloud.model.dto.Result;
import com.example.cloud.model.system.Role;
import com.example.cloud.service.system.MenuService;
import com.example.cloud.service.system.RoleService;
import com.example.cloud.utils.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wangtao on 2018/1/26.
 */
@RestController
@RequestMapping("/menu")
public class MenuController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(MenuController.class);

    @Autowired
    private RoleService roleService;

    @Autowired
    private MongoRoleRepository mongoRoleRepository;

    @Autowired
    private MenuService menuService;

    @GetMapping("/getMenus/{roleId}")
    public Result getMenus(@PathVariable Long roleId) {
        JSONArray jsonArray = new JSONArray();
        Role role = roleService.findOne(roleId);
        List<Menu> menus = menuService.findAllFromCache();
        if (role != null) {
            List<Long> ids = new ArrayList<Long>();
            for (Menu menu : role.getMenus()) {
                ids.add(menu.getId());
            }
            for (Menu menu : menus) {
                if(ids.contains(menu.getId())){
                    menu.setChecked(true);
                }
            }
            if(!menus.isEmpty()){
                jsonArray = menuService.createMenuTree(menus, null);
            }
        }
        return ResultUtil.success(jsonArray);
    }

    @PostMapping("/saveRoleMenus/{roleId}")
    public void saveRoleMenus(@PathVariable Long roleId, @RequestBody Menu menu){
        Role role = roleService.findOneFromCache(roleId);
        if(role != null){
            role.setMenus(menuService.getMenuList(role, menu));
            roleService.doSave(role);
        }
    }
}
